# coding:utf-8

from handler.api.base import BaseHandler
import pyecharts.options as opts
from pyecharts.charts import Line
from pyecharts.faker import Faker
from pyecharts.render import make_snapshot
#from snapshot_phantomjs import snapshot
from snapshot_pyppeteer import snapshot
import os
from data.mysql import mysqldb_conn

class AstringencyHandler(BaseHandler):
    def data_received(self, chunk):
        pass
    def post(self):
        pass

    """
        这是一个连接数据库，并读取表中数据的例子
    """
    def get(self):
        # 获取游标
        mysqldb_vibration_cur = mysqldb_conn.cursor()
        mysqldb_conn.ping(reconnect=True)
        # 查询用户ID
        items = []
        sql = "select * from da_astringency limit 2;"
        mysqldb_vibration_cur.execute(sql)
        for row in mysqldb_vibration_cur.fetchall():
            items.append(row)
            # print(row)
        self.write(str(items))


    """
        这是一个生成图表的例子
    """
    def get_test(self):

        c = (
            Line({"width": "320px", "height": "220px", "xAxis": {"axisLabel": {"rotate": -45}}})
            .add_xaxis(["2023/11/18 00:00", "2023/11/18 01:00", "2023/11/18 02:00", "2023/11/18 03:00"])
            .add_yaxis("时间", [6.3389, 5.3389, 4.3389, 3.3389])
            .set_global_opts(title_opts=opts.TitleOpts(title="累计变形量(mm)"), xaxis_opts=opts.AxisOpts(axislabel_opts={"rotate": -90}))
        )
        make_snapshot(snapshot, c.render(), "data.png")

        if os.path.isfile("data.png"):
            print("图像保存成功，文件路径为：" + os.path.abspath("data.png"))
        else:
            print("图像保存失败")

        with open("data.png", "rb") as f:
            image_data = f.read()

        self.set_header("Content-Type", "image-jpeg")
        self.write(image_data)
